//
//  InputBiddingView.m
//  IntelligenceCommunity
//
//  Created by zhangpei on 16/4/12.
//  Copyright © 2016年 zhangpei. All rights reserved.
//

#import "InputBiddingView.h"
#import "PublicMethod.h"
#import "UtilityConfig.h"
#import "Toast+UIView.h"
#import "ViewHelper.h"

@interface InputBiddingView()
<UITextFieldDelegate>
{
}
@property (nonatomic, copy) InputBiddingViewBlock inputBiddingViewBlock;

@property (nonatomic, assign) int maxPrice;

@property (nonatomic, assign) int floorPrice;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UIImageView *backgroundView;

@property (nonatomic, strong) UITextField *priceTextField;

@property (nonatomic, strong) UITextField *messageTextField;


@end

static  InputBiddingView * _instance_inputBiddingView;

@implementation InputBiddingView

@synthesize inputBiddingViewBlock;

@synthesize maxPrice, floorPrice;

@synthesize titleLabel, backgroundView, priceTextField, messageTextField;

+ (id)sharedInputBiddingViewWithMaxPrice:(int)max withFloorPrice:(int)floor withInputTextAlertViewBlock:(InputBiddingViewBlock)block
{
    @synchronized (self)
    {
        //为了确保多线程情况下，仍然确保实体的唯一性
        if (_instance_inputBiddingView == nil)
        {
            _instance_inputBiddingView = [[InputBiddingView alloc] init];
        }
        
        _instance_inputBiddingView.floorPrice = floor;

        [_instance_inputBiddingView setTitleLabelWithMaxPrice:max];
        
        _instance_inputBiddingView.priceTextField.text = nil;
        
        _instance_inputBiddingView.messageTextField.text = nil;

        [_instance_inputBiddingView.priceTextField becomeFirstResponder];
        
        _instance_inputBiddingView.inputBiddingViewBlock = [block copy];
        
        [WINDOW addSubview:_instance_inputBiddingView];
        
        _instance_inputBiddingView.hidden = NO;
        
        return _instance_inputBiddingView;
    }
}

+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
    {
        if (!_instance_inputBiddingView)
        {
            _instance_inputBiddingView = [super allocWithZone:zone]; //确保使用同一块内存地址
            return _instance_inputBiddingView;
        }
        return nil;
    }
}

#pragma mark - init method
#pragma mark -

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)init
{
    self = [super init];
    
    if (self)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealGetMaxBiddingPriceNotificationAction:) name:@"GETMAXBIDDINGPRICENOTIFICATION" object:nil];
        
        self.backgroundColor = [UIColor clearColor];
        
        [self initView];
    }
    return self;
}

- (void)dealGetMaxBiddingPriceNotificationAction:(NSNotification *)notification
{
    NSDictionary *dict = notification.object;
    
    int max = [[dict objectForKey:@"maxPrice"] intValue];
    
    [self setTitleLabelWithMaxPrice:max];
}


- (void)initView
{
    self.frame = WINDOW.bounds;
    
    //半透明层
    UIView *translucentView = [[UIView alloc] initWithFrame:WINDOW.bounds];
    translucentView.backgroundColor =[UIColor colorWithRed:60.f/255.f green:60.f/255.f blue:60.f/255.f alpha:1.0f];;
    translucentView.alpha = 0.5;
    [self addSubview:translucentView];
    
    backgroundView = [ViewHelper superView:self withFrame:CGRectMake(20, 0, self.bounds.size.width - 40, 0) withImage:nil withBackgroundColor:[UIColor whiteColor] withUserInteractionEnabled:YES];
    backgroundView.layer.cornerRadius = 5;
    backgroundView.clipsToBounds = YES;
    
    titleLabel = [ViewHelper superView:backgroundView
                            withFrame:CGRectMake(15, 7.5, self.bounds.size.width - 30, 30)
                             withText:@"目前最高竞拍价格0元"
                  withBackgroundColor:[UIColor clearColor]
                        withTextColor:COLORRGBA(153, 153, 153, 1)
                             withFont:[UIFont boldSystemFontOfSize:16]
                    withTextAlignment:NSTextAlignmentLeft];
    
    [titleLabel sizeToFit];
    
    NSArray *labelAry = @[@"出价",@"留言"];
    
    NSArray *placeholderAry = @[@"请输入您的出价（大于目前最高价）",@"请输入留言（不超过20字）"];
    
    UIImageView *textFieldBackgroundView = [ViewHelper superView:backgroundView withFrame:CGRectMake(15,titleLabel.frame.origin.y +titleLabel.frame.size.height + 7.5, backgroundView.bounds.size.width - 30, 45*labelAry.count + labelAry.count - 1) withImage:nil withBackgroundColor:[UIColor whiteColor] withUserInteractionEnabled:YES];
    textFieldBackgroundView.layer.cornerRadius = 7.5;
    textFieldBackgroundView.layer.borderWidth = 1;
    textFieldBackgroundView.layer.borderColor = COLORRGBA(194, 212, 212, 1).CGColor;
    
    
    for (int i = 0; i < labelAry.count; i++)
    {
        NSString *text = [labelAry objectAtIndex:i];
        NSString *placeholder = [placeholderAry objectAtIndex:i];
        
        
        UILabel *label = [ViewHelper  superView:textFieldBackgroundView withFrame:CGRectMake(5, i * 46, 40, 45) withText:text withBackgroundColor:[UIColor clearColor] withTextColor:COLORRGBA(153, 153, 153, 1) withFont:[UIFont boldSystemFontOfSize:14] withTextAlignment:NSTextAlignmentRight];
        
        //键盘类型
        UIKeyboardType keyboardType = NSNotFound;
        
        switch (i)
        {
            case 0:
                keyboardType = UIKeyboardTypeNumberPad;
                break;
            default:
                keyboardType = UIKeyboardTypeDefault;
                break;
        }
        
        UITextField* textField = [ViewHelper superView:textFieldBackgroundView
                                     withTextFieldType:TextFieldTypeOfDefault
                                             withFrame:CGRectMake(65, label.frame.origin.y, textFieldBackgroundView.bounds.size.width - 65 - 10, label.bounds.size.height)
                                      withKeyboardType:keyboardType
                                       withPlaceholder:placeholder
                                   withSecureTextEntry:NO
                                              withText:nil
                                     withReturnKeyType:UIReturnKeyDone
                                          withDelegate:self
                                   withBackgroundColor:[UIColor clearColor]
                                         withTextColor:[UIColor blackColor]
                                   withClearButtonMode:UITextFieldViewModeWhileEditing
                                              withFont:[UIFont systemFontOfSize:14]
                                     withTextAlignment:NSTextAlignmentLeft];
        
        if (i < labelAry.count - 1)
        {
            [ViewHelper superView:textFieldBackgroundView
                            withFrame:CGRectMake(label.frame.origin.x + label.frame.size.width, label.frame.origin.y, 16, 45)
                             withText:@"*"
                  withBackgroundColor:[UIColor clearColor]
                        withTextColor:[UIColor redColor]
                             withFont:[UIFont boldSystemFontOfSize:14]
                    withTextAlignment:NSTextAlignmentCenter];
            
            priceTextField = textField;

            [ViewHelper superView:textFieldBackgroundView withFrame:CGRectMake(0, label.frame.origin.y + label.frame.size.height, textFieldBackgroundView.bounds.size.width, 1) withImage:nil withBackgroundColor:COLORRGBA(221, 226, 236, 1) withUserInteractionEnabled:NO];
        }
        else
        {
            messageTextField = textField;
        }
        
    }
    
    //确定按钮
    UIButton *submitButton = [ViewHelper superView:backgroundView withFrame:CGRectMake(15, textFieldBackgroundView.frame.origin.y + textFieldBackgroundView.frame.size.height + 15, backgroundView.bounds.size.width - 30, 35) withNormalImage:nil withNormalBackgroundImage:[UIImage imageNamed:@"button_bg_green"] withBackgroundColor:nil withTitle:@"确定" withFont:[UIFont boldSystemFontOfSize:14] withTag:100 withTitleColor:[UIColor whiteColor] withTitleAlignment:NSTextAlignmentCenter];
    
    [submitButton addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    backgroundView.frame = CGRectMake(20, 0, self.bounds.size.width - 40, submitButton.frame.origin.y + submitButton.frame.size.height + 10);
    
    backgroundView.center = CGPointMake(self.center.x, self.center.y - 60);
}

- (void)setTitleLabelWithMaxPrice:(int)max
{
    self.maxPrice = max;
    
    NSString *currentPriceStr = [NSString stringWithFormat:@"目前最高竞拍价格 <font color='#FF7F00'>%d</font> 元",max];
    
    if (self.maxPrice < self.floorPrice)
    {
        currentPriceStr = [NSString stringWithFormat:@"竞拍物品底价为 <font color='#FF7F00'>%d</font> 元", self.floorPrice];
    }
    
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[currentPriceStr dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    
    _instance_inputBiddingView.titleLabel.attributedText = attrStr;
}



- (void)buttonClick:(UIButton *)button
{
    if (![PublicMethod checkStrings:priceTextField.text])
    {
        [WINDOW makeToast:@"请输入您的出价" duration:1.5f position:@"center"];

        return;
    }
    
    int price = [priceTextField.text intValue];
    
    if (maxPrice == 0)
    {
        if (price < floorPrice)
        {
            [WINDOW makeToast:@"您输入的价格小于物品底价" duration:1.5f position:@"center"];
            
            return;
        }
    }
    else
    {
        if (price <= maxPrice)
        {
            [WINDOW makeToast:@"您输入的价格小于当前最高价" duration:1.5f position:@"center"];

            return;
        }
    }
    
    
    [self hiddenKeyBoard];
    
    self.hidden = YES;

    if (inputBiddingViewBlock)
    {
        inputBiddingViewBlock(priceTextField.text, messageTextField.text);
    }
    
}


#pragma mark - 点击空白处隐藏键盘 method
#pragma mark -

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self hiddenKeyBoard];
    self.hidden = YES;
}

- (void)hiddenKeyBoard
{
    [priceTextField resignFirstResponder];
    [messageTextField resignFirstResponder];
}

#pragma mark - UITextFieldDelegate method
#pragma mark -
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
   
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if( (priceTextField == textField) && ([toBeString length] > 11))
    {
        return NO;
    }

    if( (messageTextField == textField) && ([toBeString length] > 20))
    {
        return NO;
    }
    
    return YES;
}





@end
